<template>
  <div v-loading="loading" class="user-info-container">
    <el-card class="box-card">
      <!-- <div slot="header" class="clearfix">
        <span>用户信息编辑</span>
      </div> -->

      <div class="form-container">
        <!-- 左侧头像区域 -->
        <div class="avatar-section">
          <!-- 有图片时，图片展示 -->

          <el-upload class="avatar-uploader" action="#" :http-request="httpRequest" :show-file-list="false"
            :before-upload="beforeAvatarUpload">
            <img v-if="userForm.userimg" :src="window.location.origin + userForm.userimg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="avatar-tip">建议上传正方形图片，大小不超过2MB</div>

        </div>

        <!-- 右侧表单区域 -->
        <div class="form-section">
          <el-form ref="userForm" :model="userForm" :rules="rules" label-width="100px" class="user-form">

            <!-- 基本信息 -->
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" placeholder="请输入姓名" maxlength="16" show-word-limit>
              </el-input>
            </el-form-item>

            <el-form-item label="编号" prop="code">
              <el-input :disabled="true" v-model="userForm.code" placeholder="请输入编号" maxlength="16" show-word-limit>
              </el-input>
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号" maxlength="11" show-word-limit>
              </el-input>
            </el-form-item>

            <el-form-item label="密码" prop="pwd">
              <el-input v-model="userForm.pwd" type="password" placeholder="请输入密码" show-password>
              </el-input>
            </el-form-item>

            <el-form-item label="确认密码" prop="pwdcheck">
              <el-input v-model="userForm.pwdcheck" type="password" placeholder="请再次输入密码" show-password>
              </el-input>
            </el-form-item>

            <el-form-item label="职位" prop="position">
              <el-input :value="userForm.identityid == 1 ? '管理员' : '操作员'" type="text" disabled>
              </el-input>
            </el-form-item>

            <el-form-item label="角色名称" prop="position">
              <div class="flex">
                <el-input :value="userForm.rolename" type="text" disabled>
                </el-input>
                <el-button class="ml10" @click="getUserRoleInfo" size="small" type="primary">详 情</el-button>
              </div>

            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm('userForm')">保 存</el-button>
              <!-- <el-button @click="resetForm('userForm')">重 置</el-button> -->
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>

    <roleComponent @close="dialogVisible = false" :roleData="roleForm" :dialogVisible="dialogVisible" :operType="3">
    </roleComponent>
  </div>
</template>

<script>
import { getRoleAll, fileUpload, addUpdateUser } from '@/http/api/index'
import md5 from 'md5';
import roleComponent from '@/components/role/index.vue'

export default {
  name: 'UserInfo',
  data() {

    // 手机号验证
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }

    return {
      loading: false,
      dialogVisible: false,
      roleForm: null,
      userForm: {},
      showRoleSelect: false,
      roleList: [],
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入编号', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        // password: [
        //   { required: true, validator: validatePass, trigger: 'blur' },
        //   { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        // ],
        // confirmPassword: [
        //   { required: true, validator: validatePass2, trigger: 'blur' }
        // ],
        identityid: [
          { required: true, message: '请选择职位', trigger: 'change' }
        ],
        // roleid: [
        //   { required: true, message: '请选择角色', trigger: 'change' }
        // ]
      }
    }
  },

  components: {
    roleComponent,
  },

  methods: {
    async getUserRoleInfo() {
      if (!this.roleForm) {
        this.roleForm = JSON.parse(JSON.stringify(this.$store.getters.roleInfo));
      }
      this.dialogVisible = true;
    },
    // 验证密码是否符合配置的要求
    checkPassword(value) {
      let check_difficult = this.$store.getters.baseInfo.pwd_complex;
      let min_size = this.$store.getters.baseInfo.min_pwd;

      if (value.length < min_size) {
        this.$message.error("密码长度最短 " + min_size);
        return;
      } else {
        // 需要包括大写字母
        let text = ""
        if (check_difficult.includes("0") && !/[A-Z]/.test(value)) {
          text += ",大写字母"
        }
        // 需要小写字母
        if (check_difficult.includes("1") && !/[a-z]/.test(value)) {
          text += ",小写字母"
        }
        // 需要数字
        if (check_difficult.includes("2") && !/[0-9]/.test(value)) {
          text += ",数字"
        }
        // 需要特俗字符
        if (check_difficult.includes("3") && !/[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]/.test(value)) {
          text += ",特殊字符"
        }

        if (text) {
          this.$message.error(`缺少:${text.slice(1)}`);
          return false;
        } else {
          return true;
        }
      }
    },
    // 更换头像
    httpRequest(file) {
      console.log("jinru",)
      let formdata = new FormData();
      formdata.append("file", file.file);
      fileUpload(formdata).then((res) => {
        if (res.code == 200) {
          this.userForm.userimg = res.filePath;
          this.$message.success("头像上传成功!");
        }
      }).catch(err => {
        this.$message.error("头像上传失败!");
      });
    },

    // 职位变更处理
    handlePositionChange(value) {
      this.showRoleSelect = value === 2 // 只有操作员才显示角色选择
      if (!this.showRoleSelect) {
        this.userForm.role = ''
      }
    },

    // 头像上传前的验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 提交表单
    submitForm(formName) {
      this.loading = true;
      if (!(this.userForm.id > 0)) {
        this.$message.error("数据异常");
        this.loading = false;
        return;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 这里应该调用保存用户信息的API
          if (this.userForm.pwd) {
            if (this.userForm.pwd != this.userForm.pwdcheck) {
              this.$message.error("两次密码不一致!");
              this.loading = false;
              return;
            }
            let flag = this.checkPassword(this.userForm.pwd);
            if (!flag) {
              this.loading = false;
              return;
            }

            this.userForm.pwd = md5(this.userForm.pwd);

          }
          let param = Object.assign({}, this.userForm)
          delete param.pwdcheck;
          addUpdateUser(param).then(res => {
            if (res.code == 200) {
              this.$store.commit("SET_USERINFO", Object.assign({}, this.$store.getters.userInfo, param))
              this.$message.success("保存成功");
              delete this.userForm.pwd;
              delete this.userForm.pwdcheck;
            }
            this.loading = false;
          }).catch(err => {
            this.loading = false;
            console.error(err);
          })
        } else {
          this.loading = false;
          console.log('error submit!!')
          return false
        }
      })
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.userForm.userimg = ''
    }
  },

  mounted() {
    let arr = {};
    let list = ['id', 'name', 'code', 'userimg', 'phone', 'identityid', 'rolename'];
    for (let v in this.$store.getters.userInfo) {
      if (list.includes(v)) {
        arr[v] = this.$store.getters.userInfo[v]
      }
    }
    this.userForm = arr;
  }
}
</script>

<style lang="scss" scoped>
.user-info-container {
  padding: 10px;
  height: 95%;
  overflow-y: auto;

  .box-card {
    max-width: 1000px;
    margin: 0 auto;
  }

  .form-container {
    display: flex;
    gap: 40px;
    padding: 20px;
  }

  .avatar-section {
    flex: 0 0 200px;
    text-align: center;
  }

  .form-section {
    flex: 1;
  }

  .user-form {
    max-width: 600px;
  }

  .avatar-uploader {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;

      &:hover {
        border-color: #409EFF;
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }

  .avatar {
    width: 150px;
    height: 150px;
    display: block;
    object-fit: cover;
  }

  .avatar-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 10px;
    text-align: center;
  }
}
</style>
